package com.atguigu.stgy.admin.service.impl;

import com.atguigu.stgy.admin.service.LeaseAgreementService;
import com.atguigu.stgy.model.dto.AgreementSearchDTO;
import com.atguigu.stgy.model.vo.AgreementVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.stgy.model.entity.LeaseAgreement;
import com.atguigu.stgy.admin.mapper.LeaseAgreementMapper;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class LeaseAgreementServiceImpl extends ServiceImpl<LeaseAgreementMapper, LeaseAgreement> implements LeaseAgreementService {

    @Override
    public Page<AgreementVO> pageItem(AgreementSearchDTO searchDTO) {
        //分步查询: 一步步查询AgreementVO需要的数据 再组装数据
        //项目初期：功能为主 ， 数据量较大时：需要考虑优化  不推荐写单个多表联查sql  性能差
        //  解决：缓存、异步(复杂的业务 没有原子性的操作可以使用子线程异步执行)、队列
        //1、条件查询租约分页数据
        Long provinceId = searchDTO.getProvinceId();
        Long cityId = searchDTO.getCityId();
        Long districtId = searchDTO.getDistrictId();
        Long apartmentId = searchDTO.getApartmentId();
        String roomNumber = searchDTO.getRoomNumber();
        String name = searchDTO.getName();
        String phone = searchDTO.getPhone();
        QueryWrapper<AgreementVO> wrapper = Wrappers.query();
        //为自定义sql设置条件  sql执行时会自动生成动态sql语句
/*
        WHERE t1.is_deleted = 0
          and t1.apartment_id = 9
          AND t1.phone like '%138%'
          and t1.name like '%三%'
          and t2.province_id = 11
          and t2.city_id = 1101
          and t2.district_id =  110114
          and t3.room_number LIKE '%102%'
 */
        wrapper.eq("t1.is_deleted" , 0 );
        if(apartmentId!=null){
            wrapper.eq("t1.apartment_id" , apartmentId);
        }
        if(provinceId!=null){
            wrapper.eq("t2.province_id" , provinceId);
        }
        if(cityId!=null){
            wrapper.eq("t2.city_id" , cityId);
        }
        if(districtId!=null){
            wrapper.eq("t2.district_id" , districtId);
        }
        if(StringUtils.hasLength(roomNumber)){
            wrapper.like("t3.room_number" , roomNumber);
        }
        if(StringUtils.hasLength(name)){
            wrapper.like("t1.name" , name);
        }

        if(StringUtils.hasLength(phone)){
            wrapper.like("t1.phone" , phone);
        }
        Page<AgreementVO> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());

        List<AgreementVO> agreementVOS =  baseMapper.selectAgreementVOsByCondition(page , wrapper);

        page.setRecords(agreementVOS);
        return page;
    }
}
